#!/usr/bin/perl -w

##HACKABOT_HELP##
# Set a rantom topic from a given list
# !topic [--append] [something] | --add something
##HACKABOT_HELP##

use strict;
use Hackabot::Client;

my $hbc = Hackabot::Client->new(
    ForceArray => ['prefix'],
    KeyAttr => { prefix => "+chan" });
my $conf = $hbc->{'conf'}->{'commands'}->{'topic'}->{'prefix'};
my $msg = $hbc->readline;
my $chan = $hbc->channel;
my $nick = $hbc->sent_by;

if ($msg =~ /^--add\s+(.+)/) {
    chomp $1;
    $hbc->quote_add("topic", $1);
    print "send $nick: Successfully added\n";
}
elsif ($hbc->private) {
    print "send Uh, this isn't a channel...\n";
}
else {
    my $prefix = $conf->{$chan}->{'content'};
    if (not defined $prefix) {
        $prefix = "";
    }

    if ($msg =~ /^--append\s*(.*)/) {
        $msg = $1;

        my $old = $hbc->cmd("topic");
        if ($old =~ /^ok\s*(\S+.*)/) {
            $msg = "$1 $msg";
        }
    }
    elsif (not $msg) {
        $msg = $prefix.$hbc->quote_get("topic");
    }
    else {
        $msg = $prefix.$msg;
    }

    print "topic $msg\n";
}
